/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.beyondsoft.sabg.edu.controller.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.beyondsoft.sabg.edu.model.db.core.BinaryFile;
import com.beyondsoft.sabg.edu.model.exception.GenericBusinessException;
import com.beyondsoft.sabg.edu.model.vo.core.SimpleResponseVO;
import com.beyondsoft.sabg.edu.service.core.BinaryFileService;
import com.beyondsoft.sabg.edu.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


/**
 * 文件管理
 *
 * @Author Mo cr
 * @Date 2023/11/14
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class FileController {


    @Autowired
    BinaryFileService binaryService;

    private static final String path = "/data/files/";

    /**
     * 直接存储在服务器上
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/file/store/upload", method = RequestMethod.POST)
    public SimpleResponseVO uploadToStore(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file == null) {
            return ResponseUtil.failed("file is null");
        }
        /*获取文件原名称*/
        String originalFileName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString();
        String filePath = path + fileName + ".";
        if(StrUtil.isNotEmpty(file.getContentType())){
            String[] split = file.getContentType().split("/");
            filePath += split[1];
        }
        try {
            FileUtil.writeFromStream(file.getInputStream(), filePath);
            BinaryFile fileEntity = new BinaryFile();
            fileEntity.setOriginalName(originalFileName);
            fileEntity.setFileType(file.getContentType());
            fileEntity.setStoreLocation(filePath);
            BinaryFile saved = binaryService.getRepo().save(fileEntity);
            return ResponseUtil.success().withData(saved);
        } catch (IOException e) {
            throw new GenericBusinessException("upload file failed");
        }
    }



    @RequestMapping(value = "/user/file/upload", method = RequestMethod.POST)
    public SimpleResponseVO upload(@RequestParam(value = "upload", required = false) MultipartFile file) throws IOException {

        if (file == null) {
            return ResponseUtil.failed();
        }

        BinaryFile f = binaryService.saveBinaryFile(file);

        return ResponseUtil.success().withData(f);
    }

    @RequestMapping(value = "/file/getFiles/{id}", method = RequestMethod.GET)
    public ResponseEntity getFiles(@PathVariable("id") final String fileUrlId) {
        if (fileUrlId == null) {
            throw new GenericBusinessException("file id is invalid");
        }

        Long id = null;
        try {
            String u = new String(Base64Utils.decodeFromString(fileUrlId));
            id = Long.parseLong(u);
        } catch (Exception e) {
            throw new GenericBusinessException("process error:" + e);
        }
        BinaryFile f = binaryService.findById(id).get();
        byte[] bytes = f.getBinaryContents();

        HttpHeaders responseHeaders = new HttpHeaders();
        String contentType = f.getContentType();

        responseHeaders.setContentType(MediaType.parseMediaType(contentType));
        responseHeaders.setContentLength(bytes.length);
        responseHeaders.setContentDispositionFormData("inline", id + "");

        return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/file/get/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> showImage(@PathVariable("id") final String urlId)
            throws IOException {
        if (StrUtil.isEmpty(urlId)) {
            throw new GenericBusinessException("image id is null");
        }
        Long id = null;
        try {
            String u = new String(Base64Utils.decodeFromString(urlId));
            id = Long.parseLong(u);
        } catch (Exception e) {
            log.error("Base64Utils decode urlID failed:{}", e.getMessage());
            throw new GenericBusinessException("Base64Utils decode image urlID failed:" + e.getMessage());
        }


        BinaryFile image = binaryService.findById(id).get();

        String fileName = image.getName();

        byte[] bytes = image.getBinaryContents();

        HttpHeaders responseHeaders = new HttpHeaders();
        String contentType = image.getContentType();
        if ("image/jpg".equals(image.getContentType())) {
            contentType = "image/jpeg";
        }
        responseHeaders.setContentType(MediaType.parseMediaType(contentType));
        responseHeaders.setContentLength(bytes.length);
        responseHeaders.setContentDispositionFormData("inline", id + "");

        return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
    }
}
